1792D - Fixed Prefix Permutations - CodeForces Solution


hashing math

Please click on ads to support us..

C++ Code:

#include <bits/stdc++.h>
using namespace std;

struct TrieNode {
    struct TrieNode* ch[11];
    TrieNode() {
        for (int i = 0; i < 11; i++) {
            ch[i] = nullptr;
        }
    }

    ~TrieNode() {
        for (int i = 0; i < 11; i++) {
            if (ch[i] != nullptr) {
                delete ch[i];
            }
        }
    }
};

TrieNode* root;

void add(TrieNode* node, const vector<int>& a) {
    for(int i = 0; i < a.size(); i++) {
        int id = a[i];
        if (node->ch[id] == nullptr) {
            node->ch[id] = new TrieNode;
        }

        node = node->ch[id];
    }
}

int check(TrieNode* node, const vector<int>& a) {
    int cnt = 0;
    for (int i = 0; i < a.size(); i++) {
        int id = a[i];
        if (node->ch[id] != nullptr) {
            node = node->ch[id];
            ++cnt;
        } else {
            return cnt;
        }
    }

    return cnt;
}

vector<int> div(vector<int>& a) {
    vector<int> res(a.size(), 0);
    for (int i = 0; i < a.size(); i++) {
        int id = a[i] - 1;
        res[id] = i+1;
    }

    return res;
}

void solve() {
    int n, m;
    scanf("%d%d", &n, &m);
    root = new TrieNode;
    vector<vector<int>> perms(n, vector<int>(m, 0));
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < m; j++) {
            scanf("%d", &perms[i][j]);
        }

        vector<int> c = div(perms[i]);
        add(root, c);
    }

    int ans = 0;
    for (int i = 0; i < n; i++) {
        int t = check(root, perms[i]);
        printf(i == 0 ? "%d":" %d", t);
    }

    printf("\n");
    delete root;
}

int main() {
    int t;
    scanf("%d", &t);
    while (t--) {
        solve();
    }
    return 0;
}


Comments

Submit
0 Comments
More Questions

1293B - JOE is on TV
1584A - Mathematical Addition
1660B - Vlad and Candies
1472C - Long Jumps
1293D - Aroma's Search
918A - Eleven
1237A - Balanced Rating Changes
1616A - Integer Diversity
1627B - Not Sitting
1663C - Pōja Verdon
1497A - Meximization
1633B - Minority
688B - Lovely Palindromes
66B - Petya and Countryside
1557B - Moamen and k-subarrays
540A - Combination Lock
1553C - Penalty
1474E - What Is It
1335B - Construct the String
1004B - Sonya and Exhibition
1397A - Juggling Letters
985C - Liebig's Barrels
115A - Party
746B - Decoding
1424G - Years
1663A - Who Tested
1073B - Vasya and Books
195B - After Training
455A - Boredom
1099A - Snowball